package com.azkj.album.view.fragment.detail;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.azkj.album.R;
import com.azkj.album.adapter.PicsAdapter;
import com.azkj.album.dto.GalleryBean;
import com.azkj.album.dto.ListData;
import com.azkj.album.dto.Pics;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.utils.DownLoadApkUtils;
import com.azkj.album.utils.ImageLoader;
import com.azkj.album.view.activity.DetailActivity;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.base.BaseFragment;
import com.azkj.album.view.fragment.gallery.GalleryChildFragment;
import com.azkj.album.view.widgets.dialog.ShareBottomDialog;
import com.azkj.album.view.widgets.staggedrv.GridItemDecoration;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.ImageViewerPopupView;
import com.lxj.xpopup.interfaces.OnSrcViewUpdateListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;

public class DetailFragment extends BaseFragment {

    @BindView(R.id.conver)
    ImageView conver;

    @BindView(R.id.content)
    RecyclerView content;

    @BindView(R.id.tv_not_conver)
    TextView tvNotConver;
    private boolean isCover = true;

    private PicsAdapter adapter;
    private ListData detail;

    private boolean isDownLoadAlbum;

    private ArrayList<String> selectedUrl = new ArrayList<>();

    private static CallBackListener listener;

    public static DetailFragment newInstance(boolean isCover, ListData detail, CallBackListener callBackListener) {
        DetailFragment detailFragment = new DetailFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isCover", isCover);
        bundle.putSerializable("detail", detail);
        detailFragment.setArguments(bundle);
        listener = callBackListener;
        return detailFragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        isCover = bundle.getBoolean("isCover", true);
        detail = (ListData) bundle.getSerializable("detail");
        initView();
        initData();
    }

    private void initView(){
        if (isCover){
            if (TextUtils.isEmpty(detail.getCoverImage())){
                conver.setVisibility(View.GONE);
                tvNotConver.setVisibility(View.VISIBLE);
            }else {
                conver.setVisibility(View.VISIBLE);
                tvNotConver.setVisibility(View.GONE);
            }
            conver.setVisibility(View.VISIBLE);
            content.setVisibility(View.GONE);
        }else {
            conver.setVisibility(View.GONE);
            content.setVisibility(View.VISIBLE);
            adapter = new PicsAdapter(R.layout.item_pic);
            content.setLayoutManager(new GridLayoutManager(getContext(), 4));
            content.addItemDecoration(new GridItemDecoration(getContext(), 10));
            content.setAdapter(adapter);
        }


    }

    private void initData(){
        if (isCover){
            Glide.with(this).load(detail.getCoverImage()).into(conver);
            conver.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new XPopup.Builder(getActivity())
                            .asImageViewer(conver, detail.getCoverImage(),
                                    false, -1, -1, -1,
                                    false, new ImageLoader(new Function1<Object, Unit>() {
                                        @Override
                                        public Unit invoke(Object o) {
                                            showBottomDialog(String.valueOf(o), true);
                                            return null;
                                        }
                                    }))
                            .show();
                }
            });
        }else {
            String[] pics = detail.getImages().split(",");
            ArrayList<Pics> arrayList = new ArrayList<>();
            for (String pic : pics) {
                arrayList.add(new Pics(pic, false));
            }
            adapter.setNewData(arrayList);

            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (isDownLoadAlbum) {
                        String url = ((Pics) adapter.getData().get(position)).url;
                        if (selectedUrl.contains(url)) {
                            selectedUrl.remove(url);
                        } else {
                            selectedUrl.add(url);
                        }
                        if (selectedUrl.size() == adapter.getData().size()){
                            if (listener != null){
                                listener.selectAllText("取消全选");
                            }
                        }else {
                            if (listener != null){
                                listener.selectAllText("全选");
                            }
                        }
                        ((Pics) adapter.getData().get(position)).isSelect = !((Pics) adapter.getData().get(position)).isSelect;
                        adapter.notifyItemChanged(position);
                    } else {
                        ArrayList<Pics> data = (ArrayList<Pics>) adapter.getData();
                        ArrayList<Object> urls = new ArrayList<>();
                        for (Pics datum : data) {
                            urls.add(datum.url);
                        }
                        new XPopup.Builder(getActivity())
                                .asImageViewer((ImageView) view.findViewById(R.id.iv_image), position, urls, true, false, -1, -1, -1, false, new OnSrcViewUpdateListener() {
                                    @Override
                                    public void onSrcViewUpdate(@NonNull ImageViewerPopupView popupView, int position) {
                                        if (content.getChildAt(position) != null) {
                                            popupView.updateSrcView(content.getChildAt(position).findViewById(R.id.iv_image));
                                        }

                                    }
                                }, new ImageLoader(new Function1<Object, Unit>() {
                                    @Override
                                    public Unit invoke(Object o) {
                                        showBottomDialog(String.valueOf(o), true);
                                        return null;
                                    }
                                }))
                                .show();
                    }

                }
            });
        }

    }

    private void showBottomDialog(String imgUrl, boolean isShowDownload){
        int lastSlashIndex = imgUrl.lastIndexOf("/");
        String fileName = imgUrl.substring(lastSlashIndex + 1);
        new ShareBottomDialog.Builder(getActivity())
                .setShowDownLoad(isShowDownload).setCallBack(
                        new ShareBottomDialog.Builder.ItemClickListener() {
                            @Override
                            public void onFriendClick() {
                                ((BaseActivity) getActivity()).shareImageToWx(null,imgUrl, true,-1);
                            }

                            @Override
                            public void onZoneClick() {
                                ((BaseActivity) getActivity()).shareImageToWx(null,imgUrl, false,-1);

                            }

                            @Override
                            public void onDyClick() {
                                ((BaseActivity) getActivity()).shareImgToDy(null,imgUrl, fileName,-1);

                            }
                            @Override
                            public void onDownload() {
                                downloadUrl(imgUrl, fileName);
                            }
                        }
                ).show();
    }

    private void downloadUrl(String downLoadUrl, String fileName) {
        File folder = new File(getActivity().getExternalCacheDir().getAbsoluteFile().getPath() + File.separator + "downloads");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String imageFile = fileName + ".jpg";
        File file = new File(folder, imageFile);
        if (file.exists()) {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        DownLoadApkUtils.download(downLoadUrl, file, new DownLoadApkUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.d(TAG, "onDownloadSuccess");
                ToastUtils.showCenterToast("下载成功：" + file.getAbsolutePath());
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), file.getAbsolutePath(), fileName, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
            }

            @Override
            public void onDownloading(float progress) {
                Log.d(TAG, "onDownloading  : " + progress);

            }

            @Override
            public void onDownloadFailed(String msg) {
                Log.d(TAG, "onDownloadFailed");
                ToastUtils.showCenterToast("下载失败：" + msg);
            }
        });
    }

    public ArrayList<String> getSelectedUrl(){
        return selectedUrl;
    }

    public PicsAdapter getPicsAdapter(){
        return adapter;
    }

    public void setDownLoadAlbum(boolean isDownLoadAlbum){
       this.isDownLoadAlbum = isDownLoadAlbum;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_detail;
    }

    public interface CallBackListener{
        void selectAllText(String selectAllText);
    }
}
